<?php
/**
* Copyright 2009 Waag Society <http://www.waag.org>
* This file is part of Annotrax.
*
* Annotrax is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Annotrax is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Annotrax.
* If not, see http://www.gnu.org/licenses/gpl.html
*/

?>
<?php
class Admin_MovieController extends Zend_Controller_Action{
	public function init(){
		ini_set( 'upload_max_filesize', '104857900' );
		if( !At_User::getInstance()->hasIdentity() ){
			$this->_redirect('/admin/user/login');
			exit;
		}

		$this->_helper->layout->setLayout('admin');
	}

	public function indexAction(){
		$this->_forward( 'list' );
	}

	public function editAction(){
		$request = $this->getRequest();
		$movie   = new Default_Model_Movie( $request->id );
		$channel = new Default_Model_Channel();
		$form  	 = new Admin_Form_Movie( $movie, $channel->fetchAll() );

		if( $request->isPost() && $form->isValid( $request->getPost() ) ){
			$values   = $form->getValues();
			$date	  = $values['date'];
			$channels = (array) $values['channels']['selected'];

			unset( $values['date'] );
			unset( $values['channels'] );

			$keys   = array_keys( $movie->toArray() );
			//$values = $form->getValues();

			// maybe this a stupid and lazy way of doing things.
			foreach( $values as $key => $value ){
				$camelCase = join( '', array_map( 'ucfirst', explode( '_', $key ) ) );
				$camelCase{0} = strtolower( $camelCase{0} );

				if( in_array( $camelCase, $keys ) ){
					//echo "SET $key => $value <br/>";
					$movie->$key = $value;
				}
			}

			$movie->setChannels( $channels );
			$movie->date = date('Y-m-d 00:00:00', mktime(0,0,0, $date['month'], $date['day'], $date['year']) );

			$movie->save();
			$this->_redirect( $this->view->url( array('action' => 'list', 'id' => None) ) );
			//exit;
			//$this->_redirect( '/admin/movie/list' );
		}

		$this->view->movie = $movie;
		$this->view->form  = $form;
	}

	public function deleteAction(){
		$request = $this->getRequest();
		$form	 = new Zend_Form;
		$movie	 = new Default_Model_Movie( $request->id );

		$form->addElement('submit', 'delete', array('label'	=> 'Delete' ));
		$form->addElement('submit', 'cancel', array('label'	=> 'Cancel' ));

		foreach( $form->getElements() as $element ){
			$element->removeDecorator('DtDdWrapper');
			$element->removeDecorator('Label');
		}
		$form->removeDecorator('HtmlTag');

		if( $this->getRequest()->isPost() && $form->isValid( $this->getRequest()->getPost() ) ){
			if( $request->delete !== null ){
				$filename = $movie->filename;
				$movie->delete();

				@unlink( AT_MOVIE_PATH . '/' . $filename );
			}

			$this->_redirect('/admin/movie/list');
		}

		$this->view->form 	= $form;
		$this->view->movie	= $movie;
	}

	public function addAction(){
		$request = $this->getRequest();

		$path = substr_replace( APPLICATION_PATH, 'public/movies', -(strlen('application') ) );

		if( ! file_exists( $path ) ){
			$form = '<div class="warning">' . $this->view->translate('%s does not exist!', $path ) . '</div>';
		}
		else if( !is_writable( $path ) ){
			$form = '<div class="warning">' . $this->view->translate('Cannot write to %s', $path ) . '</div>';
		}
		else{
			$form = new Admin_Form_Upload( array( 'size' => 1000, 'path' => $path, 'extension' => 'ogg,ogv,avi' ) );
		}

		$this->view->form = $form;

		if( !$form instanceof Zend_Form ){
			return;
		}

		if( $request->isPost() && $form->isValid( $request->getPost() ) ){

			$file = (object) $_FILES['uploaded_file'];

			$movie = new Default_Model_Movie(array(
				'title'			=> 'Untitled Movie',
				'subject'		=> '',
				'creator'		=> '',
				'description'	=> '',
				'publisher'		=> '',
				'date'			=> date('Y-m-d H:i:s'),
				'language'		=> 'english',
				'rights'		=> 'Creative Commons Share-A-Like',
				'filename'		=> '',
				'contributor'	=> '',
				'poster_frame'	=> 1
			));

			$movie->save();

			$ext  = rtrim( strrchr( $file->name, '.' ), '.');
			$base = substr_replace( $file->name, '', -strlen( '.' . $ext ) );
			$base = preg_replace( array('/[^a-zA-Z0-9\s]/', '/\s+/'), array(' ', '_'), trim($base) );

			$dest = sprintf( '%s/movie_%d_%s%s', $path, $movie->id, $base, $ext );

			if( move_uploaded_file( $file->tmp_name, $dest ) ){
				$movie->filename = basename($dest);
				$movie->title    = str_replace( '_', ' ', $base );
				$movie->save();
				$this->_redirect( sprintf('/admin/movie/edit/%d', $movie->id ) );
			}
			else{
				$form = '<h1>' . $this->view->translate( 'Upload failed!' ) . '<h1>';
				$movie->delete();
			}
		}
	}

	public function listAction(){
		$request = $this->getRequest();
		$movie   = new Default_Model_Movie();

		$movie->setLimit(10);
		$movie->setOffset($request->offset);

		$this->view->movie  = $movie;
		$this->view->movies = $movie->fetchAll();
	}
}
